<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="任务名称" prop="dtName">
        <el-input v-model="formData.dtName" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="关联表单" prop="dtFormId">
        <el-select
          v-model="formData.dtFormId"
          placeholder="请选择表单"
          clearable
          style="width: 100%;"
        >
          <el-option
            v-for="dict in formList"
            :key="dict.id"
            :label="dict.dfgName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="dtBeginDate">
            <el-date-picker
              v-model="formData.dtBeginDate"
              type="date"
              value-format="x"
              placeholder="选择开始时间"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="dtEndDate">
            <el-date-picker
              v-model="formData.dtEndDate"
              type="date"
              value-format="x"
              placeholder="选择结束时间"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务类型" prop="dtType">
            <el-select v-model="formData.dtType" placeholder="请选择任务类型">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_TASK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.dtType === '2'">
          <el-form-item label="周期" prop="dtPeriodType">
            <el-select v-model="formData.dtPeriodType" placeholder="请选择周期">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_TASK_PERIOD_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="formData.dtType === '2' && formData.dtPeriodType === '4'">
        <el-col :span="12">
          <el-form-item label="自定义周期时长（天）" prop="dtPeriodNum">
            <el-input v-model="formData.dtPeriodNum" placeholder="请输入自定义周期时长（天）" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="任务描述" prop="dtRemark">
        <el-input v-model="formData.dtRemark" type="textarea" placeholder="请输入任务描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TaskApi, TaskVO } from '@/api/system/task'
import { FormGroupApi, FormGroupVO } from '@/api/system/formGroup'

import { DICT_TYPE } from '@/utils/dict'
import { getStrDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'

/** 表单任务 表单 */
defineOptions({ name: 'TaskForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formList = ref<FormGroupVO[]>([])

const formData = ref({
  id: undefined,
  dtName: undefined,
  dtType: undefined,
  dtRemark: undefined,
  dtBeginDate: undefined,
  dtEndDate: undefined,
  dtFormId: undefined,
  dtPeriodType: undefined,
  dtPeriodNum: undefined,
  dtReleaseTime: undefined,
  dtShareUrl: undefined,
  dtReleaseStatus: 1
})
const formRules = reactive({
  dtName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  dtType: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
  dtBeginDate: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  dtEndDate: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  dtFormId: [{ required: true, message: '关联表单不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TaskApi.getTask(id)
    } finally {
      formLoading.value = false
    }
  }
  formList.value = await FormGroupApi.getUsedFormList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TaskVO
    if (formType.value === 'create') {
      await TaskApi.createTask(data)
      message.success(t('common.createSuccess'))
    } else {
      await TaskApi.updateTask(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    dtName: undefined,
    dtType: undefined,
    dtRemark: undefined,
    dtBeginDate: undefined,
    dtEndDate: undefined,
    dtFormId: undefined,
    dtPeriodType: undefined,
    dtPeriodNum: undefined,
    dtReleaseTime: undefined,
    dtShareUrl: undefined,
    dtReleaseStatus: 1
  }
  formRef.value?.resetFields()
}
</script>